package com.clz.latte.net;

import com.clz.latte.app.ConfigKeys;
import com.clz.latte.app.Latte;

import java.util.ArrayList;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by Administrator on 2017/11/21.
 */

public class RestCreator {

    public static final class ParamsHolder {
        private static final WeakHashMap<String, Object> PARAMS
                = new WeakHashMap<>();
    }

    public static WeakHashMap<String, Object> getParams() {
        return ParamsHolder.PARAMS;
    }

    /**
     * 构建全局RetroFit客户端
     */
    private static final class RetrofitHolder {
        private static final String BASE_URL
                = Latte.getConfiguration(ConfigKeys.API_HOST.name());
        private static final Retrofit RETROFIT
                = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(OkHttpHolder.OK_HTTP_CLIENT)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

    }

    /**
     * 构建OKHttp
     */
    private static final class OkHttpHolder {
        private static final int TIME_OUT = 60;
        private static final OkHttpClient.Builder BUILDER = new OkHttpClient.Builder();
        private static final ArrayList<Interceptor> INTERCEPTORS
                = Latte.getConfiguration(ConfigKeys.INTERCEPTOR);

        //添加拦截器
        private static OkHttpClient.Builder addInterceptor() {
            if (null != INTERCEPTORS && !INTERCEPTORS.isEmpty()) {
                for (Interceptor interceptor : INTERCEPTORS) {
                    BUILDER.addInterceptor(interceptor);
                }
            }
            return BUILDER;
        }

        private static final OkHttpClient OK_HTTP_CLIENT
                = addInterceptor()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 获取RetrofitServices
     */
    private static final class RetrofitServiceHolder {
        private static final RestServices REST_SERVICES =
                RetrofitHolder.RETROFIT.create(RestServices.class);
    }

    public static RestServices getRetrofitService() {
        return RetrofitServiceHolder.REST_SERVICES;
    }

}
